package com.woniuxy.thred.state;

/**
 * description: BlockedSleep02 <br>
 * date: 2022/2/5 5:37 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * 模拟休息
 */
public class BlockedSleep02 implements Runnable {
    //胜利者名称
    private static String winner;

    @Override
    public void run() {
        for (int steps = 1; steps <= 100; steps++) {
            //模拟休息
            if (Thread.currentThread().getName().equals("兔子") && steps % 10 == 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "-->" + steps);
            //判断是否结束了
            boolean flag = gameOver(steps);
            if (flag) {
                break;
            }
        }
    }

    private boolean gameOver(int steps) {
        if (winner != null) {
            //存在胜利者了
            return true;
        } else {
            if (steps == 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner=>" + winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        BlockedSleep02 racer = new BlockedSleep02();
        new Thread(racer, "乌龟").start();
        new Thread(racer, "兔子").start();
    }
}
